<template>
  <div class="student-container">
    <el-form :model="form" inline>
      <el-form-item prop="nickname" label="姓名:">
        <el-input v-model="form.nickname"></el-input>
      </el-form-item>
      <el-form-item prop="grade" label="班级:">
        <el-input v-model="form.grade"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="query">查询</el-button>
      </el-form-item>
    </el-form>
    <div class="opt-btns">
      <el-button type="primary" @click="addHandle">新增</el-button>
      <el-button type="Danger" :disabled="multipleSelection.length == 0" @click="batchRemove">批量删除</el-button>
    </div>
    <el-table :data="tableData" @selection-change="handleSelectionChange" border height="400">
      <el-table-column type="selection" width="55" />
          <el-table-column label="学号">
            <template #default="scope">{{ scope.row.studentNumber }}</template>
          </el-table-column>
          <el-table-column property="nickname" label="姓名"  />
          <el-table-column label="性别" width="80">
            <template #default="scope">{{ scope.row.sex ? '男': '女'  }}</template>
          </el-table-column>
          <el-table-column property="phone" label="电话" />
          <el-table-column property="QQ" label="QQ" />
          <el-table-column property="grade" label="班级" show-overflow-tooltip />
          <el-table-column fixed="right" label="操作" width="120">
            <template #default="scope">
              <el-button link type="success" size="small"
                @click="editHandle(scope.row)" >编辑</el-button
              >
              <el-button link type="Danger" size="small" @click="removeHandle(scope.row)">删除</el-button>
            </template>
      </el-table-column>
    </el-table>
    <el-pagination 
       v-if="totalData.length > 0"
       v-model:current-page="currentPage1"
       :page-size="pageNum"
       :pager-count="6" 
       style="margin-top: 20px;"
       background layout="prev, pager, next, total"
       :total="totalData.length"
       @current-change="handleCurrentChange"
    />
  </div>
  <el-dialog v-if="isOpen" v-model="isOpen" :title="editForm.id ? '编辑': '新增'" width="600">
     <AddDialog :editForm="editForm" @close-dialog="closeDialogHandle" />
  </el-dialog>
</template>

<script setup lang="ts" name="StudentList">
  import { reactive, h, ref, onMounted } from 'vue';
  import { ElTable, ElMessage, ElMessageBox } from 'element-plus'

  import AddDialog from '@/components/Student/AddDialog.vue';

  interface RuleForm {
    nickname: string,
    grade: string
  }

  interface StudentMode {
    id: string,
    studentNumber: string,
    nickname: string,
    sex: number,
    grade: string
    phone?: string,
    QQ?: string,
    isDel?: boolean
  }

  const form = reactive<RuleForm>({
    nickname: '',
    grade: ''
  })

  const currentPage1 = ref(1);

  const pageNum = ref(10);

  const handleCurrentChange = (val: number) => {
    currentPage1.value = val;
    let temp = JSON.parse(JSON.stringify(totalData));
    tableData.length = 0;
    tableData.push(...temp.slice((currentPage1.value - 1) * pageNum.value, currentPage1.value ===1 ? pageNum.value : Math.max(temp.length, pageNum.value)))
  }

  const tableData = reactive<StudentMode[]>([]);

  const totalData = reactive<StudentMode[]>([]);

  const multipleSelection = reactive<StudentMode[]>([])

  // 新增/编辑学生
  const isOpen = ref(false);
  const editForm = reactive<StudentMode>({
    id: '',
    studentNumber: '',
    nickname: '',
    sex: 1,
    grade: '',
    phone: '',
    QQ: ''
  })

  const initEditForm = (obj: StudentMode | null) => {
    editForm.id = obj?.id || '';
    editForm.studentNumber = obj?.studentNumber || '';
    editForm.nickname = obj?.nickname || '';
    editForm.sex = obj?.sex || 1;
    editForm.grade = obj?.grade || '';
    editForm.phone = obj?.phone || '';
    editForm.QQ = obj?.QQ || '';
  }

  const handleSelectionChange = (val: StudentMode[]) => {
    multipleSelection.length = 0;
    multipleSelection.push(...val);
  }

  // 新增
  const addHandle = () => {
    isOpen.value = true;
    initEditForm(null);
  }

  // 查询
  const query = () => {
    let tempData:any[] = [];
    if (form.nickname) {
      tempData = totalData.filter(item => item.nickname.indexOf(form.nickname) >= 0)
    }

    if (form.nickname && form.grade) {
      tempData = tempData.filter(item => item.grade.indexOf(form.grade) >= 0)
    }

    if(!form.nickname && form.grade) {
      tempData = totalData.filter(item => item.grade.indexOf(form.grade) >= 0)
    }

    if(!form.nickname && !form.grade) {
      tempData = [...totalData]
    }

    tableData.length = 0;
    currentPage1.value = 1;
    tableData.push(...tempData.slice((currentPage1.value - 1) * pageNum.value, pageNum.value));
  }

  // 批量删除
  const batchRemove = () => {
    totalData.forEach(item => {
      if(multipleSelection.some(cur => cur.id === item.id)) {
        item.isDel = true
      }
    })
    let tempData = JSON.parse(JSON.stringify(totalData.filter(item => !item.isDel)));
    totalData.length = 0;
    totalData.push(...tempData);
    currentPage1.value = 1;
    let temp = JSON.parse(JSON.stringify(totalData));
    tableData.length = 0;
    tableData.push(...temp.slice((currentPage1.value - 1) * pageNum.value, pageNum.value));
    multipleSelection.length = 0;
  }

  // 编辑
  const editHandle = (row: StudentMode) => {
    isOpen.value = true;
    initEditForm(row)
  }

  // 弹窗关闭的回调
  const closeDialogHandle = (data: any) => {
    isOpen.value = false;
    if(!data) return
    if(data.id) {
      let current = totalData.find(item => item.id === data.id) as StudentMode;
      Object.assign(current, { ...data })
    } else {
      totalData.push({ ...data, id: totalData.length + 1, studentNumber: 'sx12243423424' + totalData.length + 1 })
    }
    currentPage1.value = 1;
    pageNum.value = 10;
    let temp = JSON.parse(JSON.stringify(totalData));
    tableData.length = 0;
    tableData.push(...temp.slice((currentPage1.value - 1) * pageNum.value, pageNum.value));
  }

  // 单个删除
  const removeHandle = (row: StudentMode) => {
    ElMessageBox({
    title: '提示',
    message: h('p', null, [
      h('span', null, '确定 '),
      h('span', { style: 'color: red' }, '删除'),
       h('span', null, ' 此条数据吗? '),
    ]),
    showCancelButton: true,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    beforeClose: (action, instance, done) => {
      if (action === 'confirm') {
        instance.confirmButtonLoading = true
        instance.confirmButtonText = '删除中'
        setTimeout(() => {
          done()
          setTimeout(() => {
            instance.confirmButtonLoading = false
            const _index = totalData.findIndex(item => item.id === row.id);
            totalData.splice(_index, 1);
            currentPage1.value = 1;
            let temp = JSON.parse(JSON.stringify(totalData));
            tableData.length = 0;
            tableData.push(...temp.slice((currentPage1.value - 1) * pageNum.value, pageNum.value));
          }, 300)
        }, 3000)
      } else {
        done()
      }
    },
  }).then(() => {
    ElMessage({
      type: 'success',
      message: `操作成功`,
    })
    
  })
  }

  onMounted(() => {
    currentPage1.value = 1;
    pageNum.value = 10;
    let temp = JSON.parse(JSON.stringify(totalData));
    tableData.length = 0;
    totalData.length = 0;
    totalData.push(...temp);
    tableData.push(...temp.slice((currentPage1.value - 1) * pageNum.value, pageNum.value));
  })

</script>

<style lang="scss" scoped>
.student-container {
  width: 100%;
  height: 100%;
  padding-top: 20px;
  box-sizing: border-box;
  .opt-btns {
    margin-bottom: 20px;
  }
}
</style>